package parser

import (
	"bufio"
	"dict-server/db"
	"dict-server/models/dto"
	"fmt"
	"os"
	"regexp"
	"strings"
)

// 匹配单词和解释的正则表达式
var wordRegex = regexp.MustCompile(`^([A-Za-z'-]+)\s+(.+)$`)

// ParseTxtFile 解析TXT文件并返回单词列表
func ParseTxtFile(filePath string) ([]db.Word, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, fmt.Errorf("无法打开文件: %v", err)
	}
	defer file.Close()

	var words []db.Word
	scanner := bufio.NewScanner(file)
	lineNumber := 0

	// 增加缓冲区大小，处理长行
	buf := make([]byte, 1024*1024) // 1MB缓冲区
	scanner.Buffer(buf, 1024*1024)

	for scanner.Scan() {
		lineNumber++
		line := strings.TrimSpace(scanner.Text())

		// 跳过空行
		if line == "" {
			continue
		}

		// 解析行内容
		matches := wordRegex.FindStringSubmatch(line)
		if len(matches) != 3 {
			fmt.Printf("警告: 无法解析行 %d: %s\n", lineNumber, line)
			continue
		}
		// 统一转为小写
		word := strings.ToLower(matches[1])
		trans := matches[2]

		words = append(words, db.Word{
			Word:  word,
			Trans: trans,
		})
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("扫描文件错误: %v", err)
	}

	return words, nil
}

// parseExamples 从响应文本中解析出例句DTO
func ParseExamples(content string) ([]dto.Example, error) {
	var examples []dto.Example
	lines := strings.Split(content, "\n")

	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}

		// 寻找分隔符
		sepIndex := FindSeparator(line)
		if sepIndex == -1 {
			continue
		}

		// 提取中英文部分
		english := strings.TrimSpace(line[:sepIndex])
		chinese := strings.TrimSpace(line[sepIndex+1:])

		if english != "" && chinese != "" {
			examples = append(examples, dto.Example{
				English: english,
				Chinese: chinese,
			})
			if len(examples) >= 5 {
				break
			}
		}
	}

	return examples, nil
}

// findSeparator 查找中英文分隔符位置
func FindSeparator(s string) int {
	separators := []string{"||", "|", "——", "---", ":"}
	for _, sep := range separators {
		if idx := strings.Index(s, sep); idx != -1 {
			return idx + len(sep)
		}
	}
	return -1
}
